 #include"DBFile.h"

DBfile::DBfile(CString str)
{
	m_file.Open(str,CFile::modeCreate | CFile::modeNoTruncate| CFile::modeReadWrite);
}

void DBfile::setInfo(table_info* t)
{
	if(m_file&&m_file.GetLength()==0)
	{
		block_number=1;
		nondeleted.set(0,0);
		deleted.set(0,0);
		char* c=t->transformTableInfo();
		int count=((int*)c)[1];
		char content[4096];
		((int*)content)[0]=block_number;	
		((int*)content)[1]=nondeleted.block_number;
		((int*)content)[2]=nondeleted.offset;
		((int*)content)[3]=deleted.block_number;
		((int*)content)[4]=deleted.offset;
		for(int i = 0; i < count; i++)
			content[i+5*intScale] = c[i];
		m_file.Write((void *)content,4096);
	}
}

DBfile::~DBfile()
{
	m_file.Close();
}

/*int DBfile::allocNewBlock()
{
	unsigned int num = m_file.GetLength()/4096;
	unsigned int base = num * 4096;
	int content[4096/4];
	content[0]=0;		
	content[1]=4096-1;
	m_file.Seek(base, CFile::begin);
	m_file.Write((void *)content,4096);
	return num;
}

int DBfile::findEnoughSpace(int offset, int size)
{
	unsigned int block_count = m_file.GetLength() / 4096;
	int array[2];
	if(offset == 0)
		offset = 1;

	for(int i = offset; i < block_count; i++)
	{
		m_file.Seek(i*4096,CFile::begin);
		m_file.Read((void *)array,8);
		if(array[1] + 1 - 2*4 - array[0]*8 >= size + 8)
			return i;
	}
	return allocNewBlock();
}*/


